package com.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pojo.SysUser;
import com.pojo.Vo.SysUserVo;
import com.service.RoleService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    /**
     * 分页查询用户管理跳转
     * @return
     */
    @RequestMapping("/user/list")
    public Object userList(@RequestParam(defaultValue = "1")Integer pageIndex,
                           @RequestParam(defaultValue = "2")Integer pageSize,
                           @RequestParam(defaultValue = "0")Long roleId,
                           SysUserVo sysUserVo,
                           Model model){
        IPage<SysUserVo> page=new Page<SysUserVo>(pageIndex,pageSize);
        sysUserVo.setUsrRoleId(roleId);
        model.addAttribute("userPager",userService.getPage(page,sysUserVo));
        model.addAttribute("roles",roleService.list());
        model.addAttribute("usrName",sysUserVo.getUsrName());
        model.addAttribute("roleId",sysUserVo.getUsrRoleId());
        return "user/list";
    }

    /**
     * 跳转用户信息页面
     * @param model
     * @return
     */
    @RequestMapping("/user/add")
    public Object addUser(Model model){
        model.addAttribute("roles",roleService.list());
        return "user/add";
    }

    /**
     * 添加用户信息
     * @param sysUser
     * @return
     */
    @RequestMapping("/user/save")
    public Object addUserList(SysUser sysUser){
        boolean result = userService.saveOrUpdate(sysUser);
        if (result){
        return "redirect:/user/list";
        }else if (sysUser.getUsrId()==0){
            return "redirect:/user/add";
        }else {
            return "redirect:/user/edit?usrId="+sysUser.getUsrId();
        }
    }

    /**
     * 跳转修改信息页面
     * @param model
     * @return
     */
    @RequestMapping("/user/edit")
    public Object toUpdata(Long usrId,Model model){
        model.addAttribute("user",userService.getById(usrId));
        model.addAttribute("roles",roleService.list());
        return "user/edit";
    }

    @RequestMapping("/crm/user/del/{usrId}")
    @ResponseBody
    public Object del(@PathVariable long usrId){
        Map result=new HashMap();
        result.put("delResult", userService.removeById(usrId));
        return result;
    }
}